import axios from 'axios'
import store from '@/store'
import router from '@/router'
import Vue from 'vue'
import * as types from '@/store/mutation-types'
import global from './const'

let LDCOUNT = 0
let LDTIME = null
const REQTIMEOUT = 30 * 1000

// 加载BSync-START
const delay = ms => new Promise((resolve, reject) => setTimeout(() => {
  resolve()
}, ms))
const isBSync = function () {
  return window.___browserSync___
}
let BSync = isBSync()
let isController = function () {
  return BSync ? (typeof BSync._zcontroller === 'undefined' ? true : BSync._zcontroller) : true
}
const BSyncStart = function (er, cf) {
  if (BSync && cf.method === 'post') {
    if (!isController()) {
      // 设置为一个空地址
      cf._url = /^http/.test(cf.url) ? cf.url : `${cf.baseURL}${cf.url}`
      cf.url = 'https://aiapi.meishubao.com/pyai'
    }
  }
}
const BSyncEnd = async function (er, res) {
  let config = res.config
  if (BSync && config.method === 'post') {
    if (er) {
    } else {
      let tms = 500
      let total = REQTIMEOUT + 1000 * 5
      let curt = 0
      let rkey = config._url || config.url
      if (!isController()) {
        while (!BSync._zrequests[rkey]) {
          if (curt >= total) break
          await delay(tms)
          curt += tms
        }
        if (BSync._zrequests[rkey]) {
          res.data = BSync._zrequests[rkey].data
          delete BSync._zrequests[rkey]
        } else {
          res.data = {}
        }
      } else {
        BSync.socket.emit('requests', {key: rkey, data: res.data})
      }
    }
  }
}
if (BSync) {
  BSync._zrequests = {}
  BSync.socket.on('requests', function (data) {
    data.key && !isController() && (BSync._zrequests[data.key] = data)
  })
}
// 加载BSync-END

const reqStart = function (er, cf) {
  if (!isShowLoading(cf)) return false
  if (!Vue.$vux.loading.isVisible()) Vue.$vux.loading.show()
  if (LDTIME) clearTimeout(LDTIME)
  LDTIME = setTimeout(function () {
    LDCOUNT = 0
    Vue.$vux.loading.hide()
  }, cf.timeout || REQTIMEOUT)
  LDCOUNT++
}

const reqEnd = function (er, cf) {
  if (!isShowLoading(cf)) return false
  LDCOUNT--
  if (LDCOUNT <= 0) {
    LDCOUNT = 0
    Vue.$vux.loading.hide()
    clearTimeout(LDTIME)
  }
  if (er) {
    Vue.$vux.toast.text(er.message || er)
  }
}

const isShowLoading = function (cf) {
  cf = cf || {}
  const rgs = (cf.url || '').match(/[&|\\?]noloading=?([^&]*)&?/)
  if (!rgs) return true
  else return rgs[1] || ''
}

// create an axios instance
const service = axios.create({
  baseURL: global.APIURL, // api的base_url
  timeout: REQTIMEOUT // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  !!BSyncStart && BSyncStart(null, config)
  reqStart(null, config)
  // Do something before request is sent
  config.headers['X-Token'] = store.getters.user.token || '' // 让每个请求携带token-- ['X-Token']
  config.headers['X-Uid'] = store.getters.user._id || '' // 让每个请求携带uid-- ['X-Uid']
  return config
}, error => {
  reqEnd(error)
  // Do something with request error
  console.log('service.interceptors.request', error) // for debug
  return Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(async response => {
  if (BSyncEnd) {
    await BSyncEnd(null, response)
  }
  reqEnd(null, response.config)
  if (typeof response.data.code && response.data.code !== 0) {
    Vue.$vux.toast.text(response.data.msg)
    switch (response.data.code) {
      case -1:
        store.commit(types.SET_USERINFO)
        router.push('/pages/login')
        break
      case -10:
        router.push('/pages/step')
        break
    }
  }
  // 更新未读消息数
  if (typeof response.data.__URMSG_COUNT !== 'undefined') {
    store.commit(types.SET_USERINFO, {urmsg_count: response.data.__URMSG_COUNT})
  }
  return response
}, error => {
  reqEnd(error)
  console.log('service.interceptors.response.error：', error)// for debug
  return Promise.reject(error)
})

export default service
